var layer = layui.layer //弹层
    , table = layui.table //表格
    , form = layui.form,
    $ = layui.jquery,
    laydate = layui.laydate;
layui.use(['tableEdit', "excel"], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer,
        excel = layui.excel;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this
        });
    });

    function getAllJson(jsons) {
        let tmpitem = []
        for (let item of jsons) {
            let tmparr = {}
            tmparr["value"] = item["code"];
            tmparr["name"] = item["name"];
            if (item["users"]) {
                for (let it of item["users"]) {
                    item["list"].push(it)
                }
            }
            if (item["list"] && item["list"].length) {
                tmparr["children"] = getAllJson(item["list"]);
                tmpitem.push(tmparr)
            } else {
                tmpitem.push(tmparr)
            }

        }
        return tmpitem
    }

    function getxmselect(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }

    function getxmselectUser(el, name, data) {
        return xmSelect.render({
            el: el,
            name: name,
            initValue:[user.code],
            tree: {
                show: true,
                showLine: true,
                showFolderIcon: true,
                indent: 20,
                expandedKeys: false
            },
            height: 'auto',
            data: data,
            on: function ({arr, change, isAdd}) {
                return this
            }
        })
    }
    let salesmanList = [];
    let statusList = [];
    let deptList = [];
    (function () {
        //费用类型
        let costType = getdictionary(5,19);
        for(let i in costType){
            $("#costType").append("<option value=\"" + costType[i].code + "\">" + costType[i].name + "</option>");
        }

        //获取当前用户的部门及人员结构树
        let treeList = getCurrentDepartmentUser();
        statusList = getxmselect("#status", "status", [
            {name: '草稿箱', value: 1},
            {name: '待批箱', value: 2},
            {name: '已批箱', value: 3},
            {name: "终止箱", value: 6},
            {name: '完成箱', value: 4}
        ]);
        if (treeList && treeList.list) {
            let userTree = getAllJson(treeList.list);
            salesmanList = getxmselectUser("#salesmanCode", "salesmanCode", userTree);
        } else {
            salesmanList = getxmselectUser("#salesmanCode", "salesmanCode", [{name: user.name, value: user.code}]);
        }

        //获取当前用户所属部门树()
        let currentDeptTreeList = getAllUserDepartmentTree();
        if (currentDeptTreeList && currentDeptTreeList.list) {
            let deptTree = getAllJson(currentDeptTreeList.list);
            deptList = getxmselectUser("#departmentCode", "departmentCode", deptTree);
        } else {
            deptList = getxmselectUser("#departmentCode", "departmentCode", [{name: user.name, value: user.code}]);
        }

    })()

    form.render();//表单刷新
    let initData = [];
    table.render({
        elem: '#statistics'
        , data: initData
        , totalRow: true
        ,toolbar:"#statisticsToolbar"
        , cols: [[
            {field: 'numbers', width: 50, type: 'numbers', title: '序号', totalRowText: '合计'}
            , {field: 'status', title: '单据类型', sort: true, width: 200, align: 'center'}
            , {field: 'saleContractNo', title: '外销合同号', sort: true, width: 200, align: 'center'}
            , {field: 'salesmanName', title: '业务员', sort: true, width: 200, align: 'center'}
            , {field: 'costTypeName', title: '费用类型', sort: true, width: 200, align: 'center'}
            , {field: 'currency', title: '币种', sort: true, width: 200, align: 'center'}
            , {field: 'amount', title: '费用金额', sort: true, totalRow: true, width: 200, align: 'center'}
            , {field: 'amountUsd', title: '费用金额(USD)', sort: true, totalRow: true, width: 200, align: 'center'}
            , {field: 'amountRmb', title: '费用金额(RMB)', sort: true, totalRow: true, width: 200, align: 'center'}
            , {field: 'signingDateStr', title: '签约日期', sort: true, width: 200, align: 'center'}
            , {field: 'customerName', title: '客户名称', sort: true, width: 400, align: 'center'}
            , {field: 'costDesc', title: '费用描述', sort: true, width: 400, align: 'center'}

        ]]
        , id: 'statisticsTableId'
        , height: $(document).height() - $('#statistics').offset().top - 50
        , limit: 300
        , limits: [300, 600, 900]
        , page: true
    });

    form.on('submit(submit-form)', function (data) {
        if (isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptList.getValue('valueStr'))){
            data.field.salesmanCode=user.code;
        }
        table.reload('statisticsTableId', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , url: 'exportContract/statistics/getExportExpensesByPage'
            , where: data.field
        }, 'data');
        return false;
    });

    form.on('submit(exportData)', function (queryReq) {
        if (isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptList.getValue('valueStr'))){
            queryReq.field.salesmanCode=user.code;
        }
        let index = layer.load(2, {
            shade: [0.4, '#000'],
            content: '加载中...',
            success: function (layero) {
                layero.find('.layui-layer-content').css({
                    'padding-top': '40px',
                    'width': '200px'
                });
            }
        });
        $.ajax({
            data: queryReq.field,
            url: "exportContract/statistics/export/getExportExpensesExport",
            success: function (res) {
                if (res.status == 200) {
                    //配置列宽
                    let colConf = excel.makeColConfig({
                        'A': 80,
                        'X': 80
                    }, 80);
                    excel.exportExcel({
                        sheet1: res.data.data
                    }, '外销费用统计.xlsx', 'xlsx', {
                        extend: {
                            '!cols': colConf
                        }
                    });
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
                layer.close(index);
                return false;
            }
        });
        return false;
    });


    document.getElementById('clear').onclick = function () {
        statusList.setValue([]);
        salesmanList.setValue([]);
        deptList.setValue([ ]);
    };
    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }
});